# -*- coding: UTF-8 -*-
# PyCharm  main
# 2024年 02月 13日
# 作者：小帅天一
import smtplib
import re
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QFileDialog, QTableWidgetItem, QMessageBox, QVBoxLayout

from function.spider import spider_information
from CareerAnalysis import Ui_MainWindow
import pandas as pd


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ax = None
        self.fig = None
        self.canvas = None
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 初始化matplotlib图形
        self.init_matplotlib()

        # 页面跳转代码
        self.ui.pushButton_4.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.pushButton_5.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))
        # 业务逻辑代码
        self.ui.pushButton_2.clicked.connect(self.pushbutton_2)
        self.ui.pushButton_6.clicked.connect(self.pushbutton_6)
        self.ui.pushButton_7.clicked.connect(self.pushbutton_7)
        self.ui.pushButton_11.clicked.connect(self.pushbutton_11)
        self.ui.pushButton_9.clicked.connect(self.pushbutton_9)
        self.ui.pushButton_8.clicked.connect(self.pushbutton_8)
        self.ui.pushButton_10.clicked.connect(self.pushbutton_10)
        self.ui.comboBox.currentIndexChanged.connect(self.combo)
        self.ui.comboBox_2.currentIndexChanged.connect(self.combo)
        self.ui.comboBox_3.currentIndexChanged.connect(self.combo)
        self.ui.comboBox_4.currentIndexChanged.connect(self.combo)

        self.show()

    def keyReleaseEvent(self, a0: QtGui.QKeyEvent) -> None:
        """
        绑定回车键与pushbutton_2
        :param a0: 回车键
        :return:
        """
        if a0.key() == QtCore.Qt.Key_Return:
            self.pushbutton_2()

    @QtCore.pyqtSlot()
    def pushbutton_2(self):
        """
        获取数据
        :return:
        """
        # 首先清空表格内容
        self.ui.tableWidget.setRowCount(0)

        career = self.ui.lineEdit.text()
        region = self.ui.lineEdit_2.text()

        if not career or not region:
            QMessageBox.warning(self, "警告", "请输入职业和地区！", QMessageBox.Yes)
            self.ui.lineEdit.setFocus()
        else:
            csv_file = "./data/career_data.csv"
            spider_information(region, career, csv_file)
            df = pd.read_csv(csv_file, encoding="gbk")
            self.ui.tableWidget.setRowCount(df.shape[0])
            self.ui.tableWidget.setColumnCount(df.shape[1])
            self.ui.tableWidget.setHorizontalHeaderLabels(df.columns)
            # 遍历DataFrame的每一行和每一列来设置表格项
            for row_index, row in df.iterrows():
                for column_index, value in enumerate(row):
                    item = QTableWidgetItem(str(value))
                    # 使用row_index而不是row（这是一个Series对象）
                    self.ui.tableWidget.setItem(row_index, column_index, item)
            # # 调整列宽以适应内容
            # self.ui.tableWidget.resizeColumnsToContents()

    @QtCore.pyqtSlot()
    def pushbutton_6(self):
        """
        发送邮件
        :return:
        """
        career = self.ui.lineEdit.text()
        region = self.ui.lineEdit_2.text()
        mail_to = self.ui.lineEdit_3.text()
        pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
        if re.match(pattern, mail_to):
            mail_subject = f'{region}的{career}职业.csv'
            mail_from = '2416288602@qq.com'

            # QQ 邮箱 SMTP 服务器地址和端口
            smtp_server = 'smtp.qq.com'
            smtp_port = 587

            # 发件人邮箱账户名和密码
            smtp_user = '2416288602@qq.com'
            smtp_password = 'kalyuflycraxdiji'

            # 构建邮件
            msg = MIMEMultipart()
            msg['Subject'] = mail_subject
            msg['To'] = mail_to
            msg['From'] = mail_from

            # 添加邮件正文
            body = '请查收您的职业信息附件'
            msg.attach(MIMEText(body))

            # 添加CSV文件
            with open(f'./data/career_data.csv', 'rb') as f:
                part = MIMEApplication(f.read(), Name=f'{region}的{career}职业.csv')
                part['Content-Disposition'] = f'attachment; filename=f"{region}的{career}职业.csv"'
                msg.attach(part)

            # 发送邮件
            with smtplib.SMTP(smtp_server, smtp_port) as smtp:
                smtp.ehlo()
                smtp.starttls()  # 开启TLS加密传输
                smtp.login(smtp_user, smtp_password)  # 使用 login() 方法传递 SMTP 用户名和密码进行身份验证
                smtp.sendmail(mail_from, mail_to, msg.as_string())  # 将邮件发送给目标邮箱地址

            print('邮件已发送')
        else:
            QMessageBox.warning(self, "警告", "请输入正确的邮箱地址！", QMessageBox.Yes)
            self.ui.lineEdit.setFocus()

    @QtCore.pyqtSlot()
    def pushbutton_7(self):
        # 读取CSV文件
        data = pd.read_csv('./data/career_data.csv', encoding="gbk")
        mean_salaries = data.groupby('岗位要求学历')['平均薪资'].agg('mean')

        # 清除当前的Axes内容
        self.ax.clear()
        self.ax.reset_position()
        self.ax.set_aspect('auto')
        self.canvas.flush_events()

        # 绘制新的条形图
        self.ax.bar(mean_salaries.index, mean_salaries.values, color='skyblue')
        self.ax.set_xlabel('公司性质')
        self.ax.set_ylabel('平均工资(K)')
        self.ax.set_title('公司性质-平均工资比较图')
        self.ax.grid(axis='y', alpha=0.75)

        # 更新画布以显示新的图像
        self.canvas.draw()

    @QtCore.pyqtSlot()
    def pushbutton_11(self):
        # 读取CSV文件
        data = pd.read_csv('./data/career_data.csv', encoding="gbk")
        mean_salaries = data.groupby('公司性质')['平均薪资'].agg('mean')

        # 清除当前的Axes内容
        self.ax.clear()
        self.ax.reset_position()
        self.ax.set_aspect('auto')
        self.canvas.flush_events()

        # 绘制新的条形图
        self.ax.bar(mean_salaries.index, mean_salaries.values, color='skyblue')
        self.ax.set_xlabel('公司性质')
        self.ax.set_ylabel('平均工资(K)')
        self.ax.set_title('公司性质-平均工资比较图')
        self.ax.grid(axis='y', alpha=0.75)

        # 更新画布以显示新的图像
        self.canvas.draw()

    @QtCore.pyqtSlot()
    def pushbutton_9(self):
        df = pd.read_csv('./data/career_data.csv', encoding="gbk")
        # 选择“经验”这一列
        experience_column = df['岗位要求经验']

        # 计算每种经验的数量
        value_counts = experience_column.value_counts()

        # 计算每种经验的占比
        total_count = len(experience_column)
        experience_percentages = (value_counts / total_count) * 100

        # 清除当前的Axes内容
        self.ax.clear()
        self.ax.reset_position()
        self.ax.set_aspect('auto')
        self.canvas.flush_events()

        # 绘制新的饼图
        self.ax.pie(experience_percentages, labels=experience_percentages.index, autopct='%1.1f%%', startangle=90)
        self.ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        self.ax.legend(loc='upper right', fontsize=12)

        # 更新画布以显示新的图像
        self.canvas.draw()

    @QtCore.pyqtSlot()
    def pushbutton_8(self):
        df = pd.read_csv('./data/career_data.csv', encoding="gbk")
        # 选择“学历”这一列
        education_column = df['岗位要求学历']

        # 计算每种学历的数量
        value_counts = education_column.value_counts()

        # 计算每种学历的占比
        total_count = len(education_column)
        education_percentages = (value_counts / total_count) * 100

        # 清除当前的Axes内容
        self.ax.clear()
        self.ax.reset_position()
        self.ax.set_aspect('auto')
        self.canvas.flush_events()

        # 绘制新的饼图
        self.ax.pie(education_percentages, labels=education_percentages.index, autopct='%1.1f%%', startangle=90)
        self.ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        self.ax.legend(loc='upper right', fontsize=12)

        # 更新画布以显示新的图像
        self.canvas.draw()

    @QtCore.pyqtSlot()
    def pushbutton_10(self):
        df = pd.read_csv('./data/career_data.csv', encoding="gbk")
        # 选择“性质”这一列
        nation_column = df['公司性质']

        # 计算每种性质的数量
        value_counts = nation_column.value_counts()

        # 计算每种性质的占比
        total_count = len(nation_column)
        nation_percentages = (value_counts / total_count) * 100

        # 清除当前的Axes内容
        self.ax.clear()
        self.ax.reset_position()
        self.ax.set_aspect('auto')
        self.canvas.flush_events()

        # 绘制新的饼图
        self.ax.pie(nation_percentages, labels=nation_percentages.index, autopct='%1.1f%%', startangle=90)
        self.ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        self.ax.legend(loc='upper right', fontsize=12)

        # 更新画布以显示新的图像
        self.canvas.draw()

    def init_matplotlib(self):
        # 创建一个Figure和Axes对象  
        self.fig, self.ax = plt.subplots()

        # 初始化FigureCanvas对象
        plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
        self.canvas = FigureCanvas(self.fig)

        # 将FigureCanvas设置为self.ui.widget的子部件  
        layout = QVBoxLayout(self.ui.widget)
        layout.addWidget(self.canvas)

    @QtCore.pyqtSlot()
    def combo(self):
        career = self.ui.lineEdit.text()
        region = self.ui.lineEdit_2.text()
        salary = self.ui.comboBox.currentText()
        education = self.ui.comboBox_2.currentText()
        experience = self.ui.comboBox_3.currentText()
        nature = self.ui.comboBox_4.currentText()
        if not career or not region:
            QMessageBox.warning(self, "警告", "请先输入职业和地区！", QMessageBox.Yes)
            self.ui.lineEdit.setFocus()
        else:
            # 获取当前行数
            row_count = self.ui.tableWidget.rowCount()
            # 从底部开始向上删除每一行
            for row in range(row_count - 1, -1, -1):
                self.ui.tableWidget.removeRow(row)
            csv_file = "./data/career_data.csv"
            df = pd.read_csv(csv_file, encoding="gbk")
            self.ui.tableWidget.setRowCount(df.shape[0])
            self.ui.tableWidget.setColumnCount(df.shape[1])
            self.ui.tableWidget.setHorizontalHeaderLabels(df.columns)
            # 填充表格数据
            max_ask_salary = 0
            min_ask_salary = 0
            if salary != "不限":
                min_ask_salary = int(salary.split("-")[0].strip("K"))
                max_ask_salary = int(salary.split("-")[1].strip("K"))
            # print(min_ask_salary, max_ask_salary)
            min_salary = 0
            max_salary = 0
            row_ = 0
            for row_index, row in df.iterrows():
                # print(type(row))
                try:
                    if "千" in row.iloc[1].split("-")[1]:
                        min_salary = row.iloc[1].split("-")[0].split("千")[0]
                        max_salary = row.iloc[1].split("-")[1].split("·")[0].split("千")[0]
                        if "." in min_salary:
                            min_salary = int(min_salary.split(".")[0] + min_salary.split(".")[1])
                        else:
                            min_salary = int(min_salary)
                        if "." in max_salary:
                            max_salary = int(max_salary.split(".")[0] + max_salary.split(".")[1])
                        else:
                            max_salary = int(max_salary)
                        # print(min_salary)
                        # print(max_salary)
                    elif "万" in row.iloc[1].split("-")[0]:
                        min_salary = row.iloc[1].split("-")[0].split("万")[0]
                        max_salary = row.iloc[1].split("-")[1].split("·")[0].split("万")[0]
                        if "." in min_salary:
                            min_salary = int(min_salary.split(".")[0] + min_salary.split(".")[1])
                        else:
                            min_salary = int(min_salary) * 10
                        if "." in max_salary:
                            max_salary = int(max_salary.split(".")[0] + max_salary.split(".")[1])
                        else:
                            max_salary = int(max_salary) * 10
                        # print(min_salary)
                        # print(max_salary)
                    elif "千" in row.iloc[1].split("-")[0] and "万" in row.iloc[1].split("-")[1]:
                        min_salary = row.iloc[1].split("-")[0].split("千")[0]
                        max_salary = row.iloc[1].split("-")[1].split("·")[0].split("万")[0]
                        if "." in min_salary:
                            min_salary = int(min_salary.split(".")[0] + min_salary.split(".")[1])
                        else:
                            min_salary = int(min_salary)
                        if "." in max_salary:
                            max_salary = int(max_salary.split(".")[0] + max_salary.split(".")[1])
                        else:
                            max_salary = int(max_salary) * 10
                except:
                    pass
                if salary == "不限" or min_ask_salary <= min_salary and max_ask_salary >= max_salary:
                    if education == "不限" or education in str(row.iloc[2]):
                        if experience == "不限" or experience in str(row.iloc[3]):
                            if nature == "不限" or nature in str(row.iloc[7]):
                                # print(row.iloc[7])
                                for column_index, value in enumerate(row):
                                    item = QTableWidgetItem(str(value))
                                    self.ui.tableWidget.setItem(row_, column_index, item)
                                row_ += 1

                # # 调整列宽以适应内容
                # self.ui.tableWidget.resizeColumnsToContents()


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())
